﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace LoA.Shared {
	public static class GraphicMath {
		public static Vector2 AspectRatioNormalize(float aspectRatio) {
			Vector2 result = new Vector2(0, 0);
			for (int i = 1; i < 2000 && result.X == 0; i++) {
				float aspect = 1;

				if (aspectRatio >= 2) {
					int end = i - (int)Math.Ceiling(i / 2f) + 1;
					for (int j = 1; j < end && result.X == 0; j++) {
						aspect = (float)i / (float)j;
						if (aspect == aspectRatio) {
							result.X = i;
							result.Y = j;
						}
						if (aspect < 2)
							throw new Exception("Błędne porównanie: " + i.ToString( ) + " / " + j.ToString( ) + " < 2");
					}
				} else if (aspectRatio > 1) {
					int start = i - (int)Math.Ceiling(i / 2f) + 1;
					for (int j = start; j < i && result.X == 0; j++) {
						aspect = i / (float)j;
						if (aspect == aspectRatio) {
							result.X = i;
							result.Y = j;
						}
						if (aspect <= 1)
							throw new Exception("Błędne porównanie: " + i.ToString( ) + " / " + j.ToString( ) + " <= 1");
						if (aspect >= 2)
							throw new Exception("Błędne porównanie: " + i.ToString( ) + " / " + j.ToString( ) + " >= 2");
					}
				} else if (aspectRatio <= 1) {
					for (int j = i; j < 20 && result.X == 0; j++) {
						aspect = (float)i / (float)j;
						if (aspect == aspectRatio) {
							result.X = i;
							result.Y = j;
						}
						if (aspect > 1)
							throw new Exception("Błędne porównanie: " + i.ToString( ) + " / " + j.ToString( ) + " > 1");
					}
				}
			}
			if (result.X != 0 && result.Y != 0) {
				if (result.X == 8 && result.Y == 5)
					result *= 2;
				return result;
			} else
				return new Vector2(1, 1);
		}
	}
}
